<?php


namespace app\api\controller;

header('Access-Control-Allow-Origin:*');

use app\common\controller\Api;
use app\api\model\goods\Goods as GoodsModel;
use app\common\model\goods\Category as CategoryModel;
use fast\Tree;
use think\Cache;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;

class Goods extends Api
{
    protected $model = null;
    protected $noNeedLogin = ['index', 'view', 'category', 'keyword', 'comment', 'recommend'];

    /**
     * 商品列表
     * @throws DbException
     */
    public function index()
    {
        $model = new GoodsModel;
        $postData = request()->get();
        $list = $model->getGoodsList($postData);
        // 隐藏api属性
        //empty($list) && $model->hidden(['category', 'content']);
        $this->success('请求成功', $list);
    }

    /**
     * 商品详情
     * @param $id
     * @throws DbException
     */
    public function view($id)
    {
        // 商品详情
        $detail = GoodsModel::getGoodsDetail($id);

        if (!$detail || $detail['status'] != 1) {
            $this->error('很抱歉，商品不存在或已下架');
        }

        // 规格信息
        $specData = $detail['spec_type'] == 20 ? $detail->getManySpecData($detail['spec_rel'], $detail['spec']) : [];

        // 购物车数量
        if ($this->auth) {
            //$cartNum = (new CartModel())->getCartNum();
        }

        // 显示的2条评论
        $comment = 2;

        $this->success('请求成功', compact('detail', 'specData', 'comment'));
    }

    /**
     * 获取分类，将其缓存
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function category()
    {
        $app_id = 'wx401bf06bc4f58009';
        $model = new CategoryModel();
        if (!Cache::get('category_' . $app_id)) {
            $tree = Tree::instance();
            $initData = $model->where('status', '=', 1)->order('weigh desc')->select();
            $tree->init(collection((array)$initData)->toArray(), 'pid');
            $categoryData = $tree->getTreeArray(0);
            Cache::set('category_' . $app_id, $categoryData, 1800);
        }
        $this->success('请求成功', ['data' => Cache::get('category_' . $app_id)]);
    }

    /**
     * get recommend goods.
     */
    public function recommend()
    {
        //
    }

    /**
     * get goods post and qr code.
     * @param int $id
     */
    public function post($id)
    {
        //
    }

    /**
     * get goods comment and reply.
     * @param int $id
     * @return string reply list,reply count,comment percentage etc.
     */
    public function comment($id)
    {
        //
    }

    /**
     * get search keyword.
     */
    public function keyword()
    {
        //
    }
}
